package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component//放入容器
public class LoginCheckInterceptor implements HandlerInterceptor {

    //一共拦截三次,采用第一次.在进入controller之前进行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判定登录状态,如果已登录,则直接放行
        Employee employee = (Employee) request.getSession().getAttribute("SESSION_EMPLOYEE");
        if(employee != null){
            //将employ方法ThreadLocal
            EmployeeHolder.set(employee);
            return true;
        }
        //2、如果未登录,禁止通行,返回错误
        String json = JSON.toJSONString(ResultInfo.error("NOTLOGIN"));
        response.getWriter().write(json);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}
 /*//验证用户是否登录了...
        if(employee==null){
            System.out.println("用户未登录,非法访问");
            //非法访问,返回错误
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");//组装对象
            String json = new ObjectMapper().writeValueAsString(resultInfo);//转为json
            response.getWriter().write(json);//返回json
            return false;//禁止通行
        }else{

        return true;//正常放行
        }*/